<template>
  <div>
    <ZgDialog ref="dialog" :title="'单据权限设置'" :width="'700px'" :showFooter="true" @ok="onOk">
      <!-- 主流程单据 -->
      <div class="section">
        <div class="section-header">
          <span>主流程单据：</span>
          <ZgButton size="small" type="default" @click="resetMain">恢复</ZgButton>
          <ZgButton size="small" type="default" @click="toggleMainAll">{{
            mainAllSelected ? '取消全选' : '全选'
          }}</ZgButton>
        </div>
        <div class="section-body">
          <ZgCheckbox
            v-for="item in mainOptions"
            :key="item.value"
            :modelVal="mainChecked.includes(item.value)"
            @change="(val) => onMainCheckChange(item.value, val)"
          >
            {{ item.label }}
          </ZgCheckbox>
        </div>
      </div>

      <!-- 个性化单据 -->
      <div class="section">
        <div class="section-header">
          <span>个性化单据：</span>
          <ZgButton size="small" type="default" @click="resetCustom">恢复</ZgButton>
          <ZgButton size="small" type="default" @click="toggleCustomAll">{{
            customAllSelected ? '取消全选' : '全选'
          }}</ZgButton>
        </div>
        <div class="section-body">
          <ZgCheckbox
            v-for="item in customOptions"
            :key="item.value"
            :modelVal="customChecked.includes(item.value)"
            @change="(val) => onCustomCheckChange(item.value, val)"
          >
            {{ item.label }}
          </ZgCheckbox>
        </div>
      </div>

      <!-- 前置流程单单据 -->
      <div class="section">
        <div class="section-header">
          <span>前置流程单据：</span>
          <ZgButton size="small" type="default" @click="resetPre">恢复</ZgButton>
          <ZgButton size="small" type="default" @click="togglePreAll">{{
            preAllSelected ? '取消全选' : '全选'
          }}</ZgButton>
        </div>
        <div class="section-body flex-row pre-row">
          <ZgSelect v-model="preSelected" :options="preOptions" style="width: 220px" @change="onPreChange" />
          <div class="pre-checkbox-panel">
            <ZgCheckbox
              v-for="item in preData"
              :key="item.value"
              :modelVal="preChecked.includes(item.value)"
              @change="(val) => onPreCheckChange(item.value, val)"
            >
              {{ item.label }}
            </ZgCheckbox>
          </div>
        </div>
      </div>

      <!-- 合同执行单 -->
      <div class="section">
        <div class="section-header">
          <span>合同执行单：</span>
        </div>
        <div class="section-body">
          <div>
            <ZgCheckbox :modelVal="contractChecked" @change="onContractCheckChange"> 合同执行单 </ZgCheckbox>
          </div>
        </div>
      </div>
    </ZgDialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 主流程单据
      mainOptions: [],
      mainChecked: [],
      mainInit: ['1'],

      // 个性化单据
      customOptions: [],
      customChecked: [],
      customInit: [],

      // 前置流程单单据
      preOptions: [],
      preSelected: '',
      preData: [],
      preChecked: [],
      preInit: [],

      // 合同执行单
      contractChecked: false,
      currentVal: null,
      prevCheckedMap: {}, // 记录每个前置流程下拉(flowCode)的勾选项
      prevContractCheckedMap: {}, // 记录每个前置流程下拉(flowCode)的合同执行单勾选状态
      extStepConfig: null,
      prevsList: []
    }
  },
  computed: {
    mainAllSelected () {
      return this.mainChecked.length === this.mainOptions.length
    },
    customAllSelected () {
      return this.customChecked.length === this.customOptions.length && this.customOptions.length > 0
    },
    preAllSelected () {
      return this.preChecked.length === this.preData.length
    }
  },
  methods: {
    // 主流程单据
    onMainCheckChange (val, checked) {
      if (checked) {
        if (!this.mainChecked.includes(val)) this.mainChecked.push(val)
      } else {
        this.mainChecked = this.mainChecked.filter((v) => v !== val)
      }
    },
    resetMain () {
      this.mainChecked = [...this.mainInit]
    },
    toggleMainAll () {
      if (this.mainAllSelected) {
        this.mainChecked = []
      } else {
        this.mainChecked = this.mainOptions.map((i) => i.value)
      }
    },
    // 个性化单据
    onCustomCheckChange (val, checked) {
      if (checked) {
        if (!this.customChecked.includes(val)) this.customChecked.push(val)
      } else {
        this.customChecked = this.customChecked.filter((v) => v !== val)
      }
    },
    resetCustom () {
      this.customChecked = [...this.customInit]
    },
    toggleCustomAll () {
      if (this.customAllSelected) {
        this.customChecked = []
      } else {
        this.customChecked = this.customOptions.map((i) => i.value)
      }
    },
    // 前置流程单单据
    onPreCheckChange (val, checked) {
      if (checked) {
        if (!this.preChecked.includes(val)) this.preChecked.push(val)
      } else {
        this.preChecked = this.preChecked.filter(v => v !== val)
      }
      this.$set(this.prevCheckedMap, this.preSelected, [...this.preChecked])
      this.$set(this.prevContractCheckedMap, this.preSelected, this.contractChecked)
    },
    resetPre () {
      this.preChecked = [...this.preInit]
    },
    togglePreAll () {
      if (this.preAllSelected) {
        this.preChecked = []
      } else {
        this.preChecked = this.preData.map((i) => i.value)
      }
    },
    onPreChange (val) {
      // 只保留拉取数据部分（如有需要）
      const obj = this.preOptions.filter(v => v.id === val)[0]
      if (val) {
        this.$http.post('/zg-autoflow/autoflow/ext/step/form', { flowCode: obj.code }, res => {
          this.preData = res.map(v => ({
            label: v.name,
            value: v.id
          }))
        })
      } else {
        this.preData = []
      }
    },
    // 弹窗控制
    open (val) {
      this.currentVal = val
      this.$refs.dialog.open()

      // 拉取主流程单据
      this.$http.post('/zg-autoflow/autoflow/ext/step/form', { flowCode: val.flowCode }, res => {
        this.mainOptions = res.map(v => ({
          label: v.name,
          value: v.id
        }))
        this.tryRestoreOwnFlowForms()
      })
      // 拉取个性化单据
      this.$http.post('/zg-autoflow/autoflow/ext/flow/special', { flowCode: val.flowCode }, res => {
        this.customOptions = res.map(v => ({
          label: v.name,
          value: v.id
        }))
        this.tryRestoreOwnFlowForms()
      })
      // 拉取前置流程下拉
      this.$http.post('/zg-autoflow/autoflow/ext/flow/prev', { flowCode: val.flowCode }, res => {
        this.preOptions = res.map(v => ({
          label: v.name,
          value: v.id,
          ...v
        }))
        this.tryRestorePreFlowForms()
      })
      // 拉取回显配置
      this.$http.post('/zg-autoflow/autoflow/ext/step/info', { flowId: val.flowId, flowCode: val.flowCode, stepNo: val.stepNo }, res => {
        this.extStepConfig = res.extStepConfig
        this.prevsList = res.prevsList || []
        this.tryRestoreOwnFlowForms()
        this.tryRestorePreFlowForms()
      })
    },
    close () {
      // 重置所有相关选择状态
      this.mainChecked = []
      this.customChecked = []
      this.preChecked = []
      this.contractChecked = false
      this.preData = []
      this.prevCheckedMap = {}
      this.prevContractCheckedMap = {}
      this.preSelected = ''
      this.mainOptions = []
      this.customOptions = []
      this.preOptions = []
      this.currentVal = null
      this.$refs.dialog.close()
    },
    onOk () {
      // 1. 主流程单据和个性化单据的id
      const ownFlowFormsArr = [...this.mainChecked, ...this.customChecked]
      // 合同执行单不再拼接到ownFlowForms
      const ownFlowForms = ownFlowFormsArr.join(',')

      // 2. 前置流程单据集合（多组，合同执行单联动）
      const prevFlowFormArr = []
      for (const flowCode in this.prevCheckedMap) {
        let arr = this.prevCheckedMap[flowCode] || []
        // 合同执行单选中时，拼接FORM_K_HY_CNBILL（不能重复）
        if (this.contractChecked && !arr.includes('FORM_K_HY_CNBILL')) {
          arr = [...arr, 'FORM_K_HY_CNBILL']
        }
        // 合同执行单未选中时，确保没有FORM_K_HY_CNBILL
        if (!this.contractChecked) {
          arr = arr.filter(v => v !== 'FORM_K_HY_CNBILL')
        }
        if (arr && arr.length) {
          prevFlowFormArr.push({
            flowCode,
            formCode: arr.join(',')
          })
        }
      }

      // 3. 组装最终对象
      const result = {
        flowCode: this.currentVal ? this.currentVal.flowCode : '',
        flowId: this.currentVal ? this.currentVal.flowId : 0,
        ownFlowForms,
        prevFlowFormArr,
        stepNo: this.currentVal ? this.currentVal.stepNo : ''
      }
      // 你可以在这里console.log或提交result
      console.log('onOk result:', result)
      // return result
      this.$http.post('/zg-autoflow/autoflow/ext/step/saveConfig', result, res => {
        this.close()
        this.$message.success('单据权限设置成功')
      })
    },
    onContractCheckChange (val) {
      this.contractChecked = val
      this.$set(this.prevContractCheckedMap, this.preSelected, val)
    },
    tryRestoreOwnFlowForms () {
      if (
        this.mainOptions.length &&
        this.customOptions.length &&
        this.extStepConfig &&
        this.extStepConfig.ownFlowForms
      ) {
        const checkedArr = this.extStepConfig.ownFlowForms.split(',')
        this.mainChecked = this.mainOptions.filter(opt => checkedArr.includes(opt.value)).map(opt => opt.value)
        this.customChecked = this.customOptions.filter(opt => checkedArr.includes(opt.value)).map(opt => opt.value)
      }
    },
    tryRestorePreFlowForms () {
      if (this.prevsList && this.preSelected) {
        const prevItem = this.prevsList.find(item => item.prevFlowCode === this.preSelected)
        if (prevItem && prevItem.prevFlowFormCode) {
          this.preChecked = prevItem.prevFlowFormCode.split(',')
          this.contractChecked = this.preChecked.includes('FORM_K_HY_CNBILL')
        } else {
          this.preChecked = []
          this.contractChecked = false
        }
      }
    }
  },
  watch: {
    preSelected: {
      handler (newVal, oldVal) {
        // 保存旧下拉的状态
        if (oldVal) {
          this.prevCheckedMap[oldVal] = [...this.preChecked]
          this.prevContractCheckedMap[oldVal] = this.contractChecked
        }
        this.tryRestorePreFlowForms()
      },
      immediate: false
    }
  }
}
</script>

<style lang="scss" scoped>
.section {
  border: 1.5px solid #e5e5e5;
  border-radius: 10px;
  margin-bottom: 24px;
  padding: 18px 24px 18px 24px;
  background: #fff;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
}
.section-header {
  font-weight: 500;
  font-size: 15px;
  margin-bottom: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.section-header span {
  flex: 1;
  color: #222;
}
.section-header .zg-btn {
  padding: 0 12px;
  height: 28px;
  font-size: 13px;
}
.section-body {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding-bottom: 2px;
  padding-left: 0;
}
.checkbox-item {
  display: flex;
  align-items: center;
  margin-bottom: 14px;
  margin-right: 0;
  min-width: 0;
  padding-left: 0;
}
.flex-row {
  display: flex;
  align-items: flex-start;
}
.custom-empty {
  min-width: 350px;
  min-height: 90px;
  border: 1.5px dashed #d9d9d9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafbfc;
  margin-top: 2px;
}
.empty-text {
  color: #bbb;
  font-size: 14px;
  margin-top: 10px;
}
.section-body.flex-row.pre-row {
  flex-direction: row;
  align-items: flex-start;
  gap: 32px;
}
.pre-checkbox-panel {
  margin-left: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

// 分割线
.section + .section {
  border-top: none;
  margin-top: 0;
  position: relative;
}
.section + .section:before {
  content: '';
  display: block;
  position: absolute;
  left: 24px;
  right: 24px;
  top: -12px;
  height: 1px;
  background: #f0f0f0;
  z-index: 1;
}

.custom-btns .zg-btn,
.section-header .zg-btn {
  transition: none !important;
  box-shadow: none !important;
}
.custom-btns .zg-btn:active,
.section-header .zg-btn:active,
.custom-btns .zg-btn:focus,
.section-header .zg-btn:focus {
  background: inherit !important;
  border-color: #d9d9d9 !important;
  color: inherit !important;
  box-shadow: none !important;
}
::v-deep .ant-checkbox-wrapper {
  margin-left: 0 !important;
}
</style>
